﻿using Coldairarrow.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Util;

namespace API.Controllers
{
    [Route("/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class BaseController : ControllerBase
    {
        // 用户ID 
        protected string CurrentUserId => User.FindFirstValue("Uid") ?? "";
        // 手机号 
        protected string CurrentPhone => User.FindFirstValue("phone") ?? "";// 手机号 
        public BaseController()
        {
        }
        /// <summary>
        /// 验证表名并返回缺失或无效字段的信息
        /// </summary>
        /// <param name="model">包含表名的对象</param>
        /// <returns>ActionResult</returns>
        //protected async Task<ResultMsg<string>> ValidateAndTranslateFieldsAsync(FieldTranslation model)
        //{
        //    var result = new ResultMsg<string>();

        //    if (!ModelState.IsValid)
        //    {
        //        var errors = ModelState.Values.SelectMany(v => v.Errors)
        //            .Select(e => e.ErrorMessage)
        //            .ToList();

        //        return result.Error(JsonConvert.SerializeObject(errors));
        //    }

        //    if (!IsValidTableName(model.TableName))
        //    {
        //        return result.Error($"找不到{model.TableName}表.");
        //    }

        //    // 获取字段翻译信息
        //    var fieldTranslationsTask = _fieldTranslationService.GetFieldTranslationsAsync(model.TableName);
        //    var fieldTranslations = await fieldTranslationsTask;

        //    // 假设我们需要验证某些字段的有效性
        //    var validationResults = new List<ValidationResult>();
        //    var validationContext = new ValidationContext(model);

        //    var validationSuccess = Validator.TryValidateObject(validationContext.ObjectInstance, validationContext, validationResults, true);

        //    if (!validationSuccess)
        //    {
        //        var missingFields = validationResults
        //            .SelectMany(vr => vr.MemberNames) // 使用 SelectMany 来展开 MemberNames
        //            .Distinct()
        //            .Select(fieldName => new
        //            {
        //                FieldName = fieldName,
        //                ChineseName = fieldTranslations.ContainsKey(fieldName) ? fieldTranslations[fieldName] : fieldName
        //            })
        //            .ToList();

        //        return result.Error(JsonConvert.SerializeObject(missingFields));
        //    }

        //    return result; // 如果没有错误，返回成功结果
        //}

        private bool IsValidTableName(string tableName)
        {
            // 这里可以添加具体的表名验证逻辑，例如正则表达式检查
            return !string.IsNullOrWhiteSpace(tableName) && tableName.Length <= 128;
        }
        /// <summary>
        /// 获取当前Token
        /// </summary>
        /// <returns></returns>
        protected string GetCurrentToken()
        {
            var authorizationHeader = Request.Headers["Authorization"].FirstOrDefault();
            if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
            {
                return authorizationHeader.Substring("Bearer ".Length).Trim();
            }

            return null;
        }
        /// <summary>
        /// 初始化实体
        /// </summary>
        /// <param name="obj"></param>
        protected void InitEntity(object obj)
        {
            // 获取当前 Id 的值
            var currentId = obj.GetPropertyValue("Id");

            // 检查 Id 是否为空
            if (currentId == null || string.IsNullOrEmpty(currentId.ToString()))
            {
                // 如果 Id 为空，则设置新的 Id
                obj.SetPropertyValue("Id", IdHelper.GetId());
            }
            //if (obj.ContainsProperty("Id"))
            //    obj.SetPropertyValue("Id", IdHelper.GetId());
            if (obj.ContainsProperty("CreateTime"))
                obj.SetPropertyValue("CreateTime", DateTime.Now);
            if (obj.ContainsProperty("CreatorId"))
                obj.SetPropertyValue("CreatorId", CurrentUserId);
        }
    }
}
